package com.yikaiye.android.yikaiye.ui.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.base.BaseFragment;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.FragmentAllOrderBinding;
import com.yikaiye.android.yikaiye.ui.adapter.ServiceAdapter;
import com.yikaiye.android.yikaiye.ui.fragment.viewmodel.ServiceListViewModel;

/**
 * 不同状态的服务列表
 */
public class ServiceStatusFragment extends BaseFragment<FragmentAllOrderBinding, ServiceListViewModel> {
    private ServiceAdapter adapter;
    /**
     * 服务状态：0.待办 1.在办 2.暂停 3.已办结 4.已终止
     */
    private String status;
    private int page = 1;

    public static ServiceStatusFragment newInstance(String status) {
        Bundle bundle = new Bundle();
        bundle.putString(Constant.STATUS_KEY, status);
        ServiceStatusFragment fragment = new ServiceStatusFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected ServiceListViewModel bindModel() {
        return getViewModel(this, ServiceListViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initData() {
        if (getArguments() != null) {
            status = getArguments().getString(Constant.STATUS_KEY, null);
        }
    }

    @Override
    public void lazyLoadData() {
        adapter = new ServiceAdapter(mContext);
        binding.recyclerView.setAdapter(adapter);
        adapter.setEmptyViewEnable(true);
        adapter.setEmptyViewLayout(mContext, R.layout.layout_empty_list);
        viewModel.getServiceList(page, status);
    }

    @Override
    protected void initClick() {
        // 服务列表数据
        viewModel.serviceRecordsModelMutableLiveData.observe(this, serviceRecordsModel -> {
            if (serviceRecordsModel != null) {
                if (page == 1) {
                    adapter.submitList(serviceRecordsModel.getRecords());
                    binding.smartRefreshLayout.finishRefresh();
                } else {
                    adapter.addAll(serviceRecordsModel.getRecords());
                    binding.smartRefreshLayout.finishLoadMore();
                }
            }
        });

        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                viewModel.getServiceList(page, status);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                viewModel.getServiceList(page, status);
            }
        });
    }
}
